package cn.ctbu.xiaopeng.studentscoremanage.interceptor;

import cn.ctbu.xiaopeng.studentscoremanage.dao.UserRepository;
import cn.ctbu.xiaopeng.studentscoremanage.pojo.entity.User;
import cn.ctbu.xiaopeng.studentscoremanage.utils.ResultUtils;
import cn.ctbu.xiaopeng.studentscoremanage.utils.UserContextHolder;
import com.alibaba.fastjson.JSON;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author xiaopeng
 * @version 1.0
 */
@Slf4j
@RequiredArgsConstructor // 这个注解会自动生成带有 `UserRepository` 参数的构造器
public class UserTypeInterceptor implements HandlerInterceptor {

    private final UserRepository userRepository;

    private static final String[] Interceptor_Teacher_View_URLS = {
            "/user/userInfoManager", "/operateLog"
    };

    private static final String[] Interceptor_Teacher_API_URLS = {
            //教师管理相关
            "/api/teacher/add", "/api/teacher/delete", "/api/teacher/delete/batch",
            "/api/teacher/update",

            //教师选课相关
            "/api/tc/delete", "/api/tc/delete/batch", "/api/tc/update"
    };

    private static final String[] Interceptor_Student_View_URLS = {
            "/user/userInfoManager", "/operateLog", "/tc/TCManager", "/teacher/teacherInfoManager"
            , "/score/ScoreManager", "/student/stuManager"
    };

    private static final String[] Interceptor_Student_API_URLS = {
            // 课程相关
            "/api/course/add", "/api/course/delete", "/api/course/delete/batch"
            , "/api/course/update",
            // 学生选课相关
            "/api/sc/delete", "/api/sc/delete/batch", "/api/sc/update"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求url。
        String url = request.getRequestURL().toString();
        log.info("请求的url: {}", url);

        //获取当前用户
        String userName = UserContextHolder.getUserName();

        log.info("当前用户: {}", userName);

        if (userName == null) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ResultUtils.error(401, "未登录")));
            response.sendRedirect("/error.html"); //重定向到错误页面
            return false;
        }

        User user = userRepository.findByUserName(userName);

        if (user == null) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ResultUtils.error(404, "用户不存在")));
            response.sendRedirect("/error.html"); //重定向到错误页面
            return false;
        }

        if (user.getUserType() == 1) {
            return true;
        }

        if (user.getUserType() == 2) { // 教师
            for (String s : Interceptor_Teacher_View_URLS) {
                if (url.contains(s)) {
                    response.sendRedirect("/error/error.html"); //重定向到错误页面
                    return false;
                }
            }
            for (String s : Interceptor_Teacher_API_URLS) {
                if (url.contains(s)) {
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(JSON.toJSONString(ResultUtils.error(403, "教师无权限执行此操作")));
                    return false;
                }
            }
        }

        if (user.getUserType() == 3) { // 学生
            for (String s : Interceptor_Student_View_URLS) {
                if (url.contains(s)) {
                    response.sendRedirect("/error/error.html"); //重定向到错误页面
                    return false;
                }
            }
            for (String s : Interceptor_Student_API_URLS) {
                if (url.contains(s)) {
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(JSON.toJSONString(ResultUtils.error(403, "学生无权限执行此操作")));
                    return false;
                }
            }
        }

        return true;
    }
}
